package com.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class CharBufferDemo {

	private static final int BSIZE = 1024;

	public static void main(String[] args) throws IOException {
		FileChannel fc = new FileOutputStream("c:/bb.txt").getChannel();
		fc.write(ByteBuffer.wrap("张三李四".getBytes()));
		fc.close();

		fc = new FileInputStream("c:/bb.txt").getChannel();
		ByteBuffer buff = ByteBuffer.allocate(BSIZE);
		fc.read(buff);
		buff.flip();
		// 输出有问题
		System.out.println(buff.asCharBuffer());

		// 对缓冲器调用rewind方法，目的是返回到数据开始部分
		buff.rewind();
		String encoding = System.getProperty("file.encoding");
		// Charset类提供了把数据编码成多种不同类型的字符集的工具
		System.out.println("Decoded using " + encoding + ": "
				+ Charset.forName(encoding).decode(buff));

		fc = new FileOutputStream("c:/cc.txt").getChannel();
		fc.write(ByteBuffer.wrap("张三".getBytes(Charset.forName(encoding))));
		fc.close();

		fc = new FileInputStream("c:/cc.txt").getChannel();
		buff.clear();
		fc.read(buff);
		buff.flip();
		// 输出时，用CharBuffer输出
		System.out.println(Charset.forName(encoding).decode(buff));

		// 通过CharBuffer向ByteBuffer写入
		fc = new FileOutputStream("c:/dd.txt").getChannel();
		// 为ByteBuffer分配了24个字节，但一个字符需要2个字节，那么一个ByteBuffer可以容纳12个字符，剩余的内容为0的字节仍会生成并输出
		buff = ByteBuffer.allocate(24);
		buff.asCharBuffer().put("李四");
		fc.write(buff);
		fc.close();

		fc = new FileInputStream("c:/dd.txt").getChannel();
		buff.clear();
		fc.read(buff);
		buff.flip();
		System.out.println(buff.asCharBuffer());
	}

}
